import { createToast } from '../../common/toast.js';
import { handleKubectlCore, navigateToKubectl } from '../../common/kubectl-handler.js';

export async function handleKubectlNavigation() {
    // 获取当前标签页
    const tabs = await chrome.tabs.query({active: true, currentWindow: true});
    const currentTab = tabs[0];
    const currentUrl = currentTab.url;

    // 使用核心逻辑处理URL
    const result = await handleKubectlCore(currentUrl);
    if (!result.success) {
        createToast?.(result.error, 'error');
        return;
    }

    try {
        // 获取配置的打开方式
        const { kubectlOpenType = 'tab' } = await chrome.storage.local.get(['kubectlOpenType']);
        
        await navigateToKubectl(currentTab, result.targetUrl, kubectlOpenType);

        // 根据打开方式显示不同的提示
        const messages = {
            current: '正在打开 kubectl 终端...',
            window: '已在新窗口打开 kubectl 终端',
            tab: '已在新标签页打开 kubectl 终端'
        };
        createToast?.(messages[kubectlOpenType] || messages.tab, 'success');
    } catch (error) {
        createToast?.('打开终端失败，请重试', 'error');
        console.error('打开终端失败:', error);
    }
} 